package org.phoenixframework.common.security.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.phoenixframework.common.tools.Constants;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2021/5/6 21:57
 * Description:
 */
@Component
public class TokenManager {

    public String createToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + Constants.TOKEN_EXPIRATION))
                .signWith(SignatureAlgorithm.HS512, Constants.JWT_SIGNING_KEY).compressWith(CompressionCodecs.GZIP).compact();
    }

    public String getUserIdByToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(Constants.JWT_SIGNING_KEY).parseClaimsJws(token).getBody();
        return claims.get(Constants.USER_ID, String.class);
    }

    public String getUsernameByToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(Constants.JWT_SIGNING_KEY).parseClaimsJws(token).getBody();
        return claims.get(Constants.USERNAME, String.class);
    }

}
